const webSocket = require('ws');
const path = require('path');
const fileUtils = require('../utils/files_utils');
// 创建webSocket服务端对象，绑定端口号3001
const wss = new webSocket.Server({
    port: 3001
});

module.exports.listen = () => {
    wss.on('connection', client => {
        console.log('连接成功');
        client.on('message', async msg => {
            let payload = JSON.parse(msg);
            const action = payload.action;
            if (action === 'getData') {
                let filePath = '../data/' + payload.chartName + '.json';
                filePath = path.join(__dirname, filePath);
                const ret = await fileUtils.readJsonData(filePath);
                payload.data = ret;
                client.send(JSON.stringify(payload));
            } else {
                wss.clients.forEach(client => {
                    client.send(msg);
                })  
            }
        })
    })
}